package com.MyDemo.demo.controller;

import com.MyDemo.demo.domain.dto.LoginDTO;
import com.MyDemo.demo.domain.dto.RedisTestDTO;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.security.Keys;
import io.jsonwebtoken.security.SignatureAlgorithm;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.tags.Tag;

import java.nio.charset.StandardCharsets;
import java.util.HashMap;

import javax.crypto.SecretKey;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

// 定义请求路径为/wt，并标识该类为REST控制器
@RequestMapping("/wt")
@RestController
@Tag(name = "测试name")
public class ControllerDemo {
    Logger logger = LoggerFactory.getLogger(ControllerDemo.class);

    // 自动注入RedisTemplate实例，用于操作Redis数据库
    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    /**
     * 处理GET请求，路径为/demo
     * 
     * @return 返回字符串"hello"
     */
    @GetMapping("/demo")
    @Operation(description = "测试description")
    @ApiResponse(description = "存入redis")
    public String func1() {
        // 获取Redis的ValueOperations对象，用于操作字符串类型的键值对
        ValueOperations<String, String> stringStringValueOperations = redisTemplate.opsForValue();
        // 将键"a"对应的值设置为"1"
        stringStringValueOperations.set("a", "1");
        // 返回字符串"hello"
        return "hello";
    }

    /**
     * 处理POST请求
     * 
     * @param redisTestDTO 包含要存入Redis的数据的DTO对象
     */
    @PostMapping("put-to-redis")
    @Operation(description = "向redis中添加数据")
    public void func2(@RequestBody RedisTestDTO redisTestDTO) {
        logger.info("dto");
        // 将数据存入Redis的Hash结构中，键为"MyTestKey"，字段为redisTestDTO.getKey()，值为redisTestDTO.getValue()
        redisTemplate.opsForHash().put("MyTestKey", redisTestDTO.getKey(), redisTestDTO.getValue());
    }

    @PostMapping("/login")
    @Operation(description = "登录")
    /* public String login(@RequestBody LoginDTO loginDTO) { */
    public String login(@RequestBody LoginDTO loginDTO) {
        SecretKey key = Keys.hmacShaKeyFor("itwt12341234asdfasdf12341234123412341234".getBytes(StandardCharsets.UTF_8));
        HashMap<String, String> hashMap = new HashMap<>();
        hashMap.put("username", "wt");
        hashMap.put("age", "25");
        String jws = Jwts.builder().claims(hashMap).signWith(key).compact();
        return jws;
    }
}